import { window, Range } from "vscode";
import { createDecoration } from "./colorDecoration";
/**
 * 一个处理颜色的工具类，方便文本中的颜色代码选取，查看。
 * 如文本中有颜色代码 “&lt;fac&gt;”，把 “&lt;fac&gt;” 显示为粉色
 * 鼠标悬浮时，弹出颜色选择框，点击指定颜色时切换为指定颜色的代码。
 * 暂时只考虑 Mud 基本颜色。
 */

var colorDecortion = {
    decs: {}, // {colorCode:{dec:DT,ranges:[]}}
    timer: null
}

export function listener() {
    if (colorDecortion.timer) {
        clearTimeout(colorDecortion.timer)
    }
    colorDecortion.timer = setTimeout(() => {
        colorDecortion.timer = null;
        colors();
    }, 1000)
}

// 设置颜色代码颜色
export function colors() {
    const reg = new RegExp("\\<([fb][0-9a-f]{6}|[fb][0-9a-f]{3}|g([01][0-9]|2[0-3])|[a-f]{3}|[0-8][0-9]{2})\\>", "ig")
    const editor = window.activeTextEditor
    const doc = editor.document
    const text = doc.getText()
    clear()
    let m;
    while ((m = reg.exec(text)) != null) {
        const scl = m[1]
        // console.log(m)
        if (!colorDecortion.decs[scl]) {
            colorDecortion.decs[scl] = {
                "dec": createDecoration(scl),
                "ranges": []
            }
        }
        const startPos = doc.positionAt(m.index);
        const endPos = doc.positionAt(m.index + m[0].length);
        const range = new Range(startPos, endPos)
        colorDecortion.decs[scl]["ranges"].push(range)
    }

    for (let key in colorDecortion.decs) {
        if (!colorDecortion.decs[key] || !colorDecortion.decs[key]["ranges"] || !colorDecortion.decs[key]["dec"]) {
            continue
        }
        editor.setDecorations(colorDecortion.decs[key]["dec"], colorDecortion.decs[key]["ranges"])
    }

}

/**
 * 清除装饰器对应的范围列表
 */
export function clear() {
    for (let key in colorDecortion.decs) {
        colorDecortion.decs[key]["ranges"] = []
    }
}
